import axios from 'axios';

interface IpInfo {
  ip: string;
  country: string;
  regionName:string;
  deviceType: string;
}

export function useIpApi() {
  /**
   * 获取IP信息
   * @param ip 可选的IP地址，如果不提供则获取当前用户的IP
   * @returns IP信息对象
   */
  const getIpInfo = async (ip?: string): Promise<IpInfo> => {
    try {
      // 构建API URL，如果提供了IP则使用它
      const baseUrl = 'http://ip-api.com/json';
      const url = ip ? `${baseUrl}/${ip}` : baseUrl;
      
      const response = await axios.get(url, {
        params: {
          fields: 'query,country,regionName,status'
        }
      });
      const data = response.data;
      console.log('response',response)
      console.log('data',data);
      
      if (data.status === 'fail') {
        throw new Error(data.message || '获取IP信息失败');
      }
      
      // 检测设备类型
      const userAgent = navigator.userAgent.toLowerCase();
      let deviceType = 'Other';
      
      if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(userAgent)) {
        deviceType = 'Tablet';
      } else if (/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(userAgent)) {
        deviceType = 'Mobile';
      } else if (/windows|macintosh|linux/i.test(userAgent)) {
        deviceType = 'PC';
      }

      return {
        ip: data.query,
        country: data.country,
        regionName:data.regionName,
        deviceType
      };
    } catch (error: any) {
      console.error('获取IP信息失败:', error);
      // 如果是网络错误，提供更具体的错误信息
      if (error.response) {
        throw new Error(`请求失败: ${error.response.status} - ${error.response.statusText}`);
      } else if (error.request) {
        throw new Error('网络请求失败，请检查网络连接');
      }
      throw error;
    }
  };

  return {
    getIpInfo
  };
}